import React, { useEffect, useState } from 'react'
import ProForm, { ProFormSelect, ProFormText, } from '@ant-design/pro-form'
import { Input, TreeSelect } from 'antd'
import { categoryList } from '@/services/category'
import Modal from 'antd/es/modal/Modal'
import ProFormItem from '@ant-design/pro-form/es/components/FormItem'

function CreateForm (props) {
  /** 获取父类数据 **/
  const { createModalVisit, setCreateModalVisit, group, treeData, createCategory, categoryLists } = props
  /** 获取分组信息数据 **/
  const [children, setChildren] = useState([])

  useEffect(() => {
    setChildren(treeData(categoryLists))
  }, [categoryLists])

  /**
   * 更换树状图
   * @param value
   * @returns {Promise<void>}
   */
  const onSelected = async value => {
    /** 获取科目分组 **/
    const data = await categoryList({ category_group: value })
    setChildren(treeData(data))
  }

  return (
    <Modal
      forceRender={true}
      preserve={false}
      title="新建分类"
      visible={createModalVisit}
      onCancel={setCreateModalVisit}
      layout={'inline'}
      size="small"
      width={520}
      footer={null}
    >
      <ProForm
        onFinish={values => createCategory(values)}
      >
        <ProFormSelect
          name="category_group"
          label="选择分组"
          initialValue={props.initialValue}
          valueEnum={group}
          fieldProps={{ onSelect: (e) => onSelected(e) }}
          rules={[
            { required: true, message: '请选择分组' },
          ]}
        />
        <ProFormItem
          name="pid"
          label="选择父级"
          rules={[
            { required: true, message: '请选择分类' },
          ]}
        >
          <TreeSelect
            placeholder="选择分类"
            treeData={children}
          />
        </ProFormItem>
        <ProFormText
          name="name"
          label="分类名称"
          placeholder="请输入2位到24位的名称"
          rules={[
            { required: true, message: '请填写分类名称' },
            { min: 2, message: '分类名称最少需要2位' },
            { max: 24, message: '分类名称最多只能24位' },
          ]}
        >
          <Input/>
        </ProFormText>
      </ProForm>
    </Modal>
  )
}

export default CreateForm
